package com.imooc.sell.controller;

import com.google.gson.Gson;
import com.imooc.sell.VO.pan.*;
import com.imooc.sell.dao.RemarkDao;
import com.imooc.sell.dataobject.Remark;
import com.imooc.sell.service.RemarkService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.regex.Pattern;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/remark")
public class RemarkController {
    @SuppressWarnings("all")
    public static final Logger logger = LoggerFactory.getLogger(RemarkController.class);
    private final RemarkService remarkService;

    @Autowired
    public RemarkController(RemarkService remarkService) {
        this.remarkService = remarkService;
    }


    /**
     * 用户添加一条评论
     *
     * @param addRemark 前端传过来的数据
     * @return 返回Gson包装好的Json字符串
     */
    @PostMapping("/add")
    public String addRemark(@RequestBody AddRemark addRemark) {
        Remark remark = new Remark();
        remark.setComment(addRemark.getComment());
        remark.setOrderId(addRemark.getOrderId());
        remark.setNickName(addRemark.getUserInfo().getNickName());
        remark.setHeadImg(addRemark.getUserInfo().getHeadImg());
        Gson gson = new Gson();
        return gson.toJson(remarkService.addRemark(remark));
    }

    /**
     * 客户端查询所有评论
     *
     * @return 返回一个Json字符串
     */
    @GetMapping("/remarklist")
    @CrossOrigin
    public String getAll(/*HttpServletResponse response*/) {
        Gson gson = new Gson();
        RemarkResult result = remarkService.getAll();
        RemarkRemarkMap remarkRemarkMap = new RemarkRemarkMap(1, "成功", result.getRemarkList());
        return gson.toJson(remarkRemarkMap);
    }

    /**
     * 客户端更新一条评论
     *
     * @param remark 评论实体类的属性与请求中的同名参数对应
     * @return 返回封装结果类RemarkResult2
     */
    @PostMapping("/update")
    public String updataRemark(@RequestBody Remark remark) {
        Gson gson = new Gson();
        return gson.toJson(remarkService.updataRemark(remark));
    }

    /**
     * 客户端根据订单号获取评论
     *
     * @param orderId 订单号
     * @return 返回一个自定义封装结果类
     */
    @GetMapping("/byOrderId")
    public String getAllByOrderId(@RequestParam(value = "orderId", required = false, defaultValue = "0") String orderId) {
        Gson gson = new Gson();
        return gson.toJson(remarkService.getAllRemarkById(orderId));
    }

    /**
     * 后台添加评论，添加后直接返回总评论页面
     *
     * @param remark 后台上传的评论表单
     * @return 返回视图ModelAndView，跳转到所有评论页面
     */

    @RequestMapping("/admin/add")
    public ModelAndView addRemarkAdmin(@ModelAttribute Remark remark, @RequestParam String openid, @RequestParam String page) {
        RemarkResult2 rr2 = remarkService.addRemarkAdmin(remark);
        //jumpToRemarkList方法用与向所有评论详情页跳转
        /*return rr2;*/
        return jumpToRemarkList(rr2, openid, page);
    }

    /**
     * 后台在查询页面添加评论，此处与总评论页面添加评论不是同一接口
     *
     * @param remark 后台上传的评论表单
     * @return 返回视图ModelAndView，跳转到通过查询orderId得到的所有评论的页面
     */
    @RequestMapping("/admin/addbyid")
    public ModelAndView addRemarkAdminById(@ModelAttribute Remark remark, @RequestParam String openid) {
        RemarkResult2 rr2 = remarkService.addRemarkAdmin(remark);
        //jumpToOrderIdRemarkList方法用于向查询某订单的评论详情页面
        return jumpToOrderIdRemarkList(rr2, remark.getOrderId(), openid);
    }

    @RequestMapping("/admin/addintimescope")
    @SuppressWarnings("all")
    public ModelAndView addRemarkAdminInTimeScope(@ModelAttribute Remark remark, @RequestParam String page, @RequestParam String openid) {
        RemarkResult2 rr2 = remarkService.addRemarkAdmin(remark);
        //jumpToOrderIdRemarkList方法用于向查询某订单的评论详情页面
        return jumpToRemarkList(rr2, lastStartTime, lastEndTime, page, openid);
    }

    /**
     * 后台删除一条评论
     *
     * @param remarkId 评论Id号
     * @return 返回视图ModelAndView，跳转到所有评论页面
     */
    @RequestMapping("/admin/delete")
    public ModelAndView deleteRemarkAdmin(@RequestParam String remarkId, @RequestParam String openid, @RequestParam String page) {
        RemarkResult2 rr2 = remarkService.deleteRemark(remarkId);
        return jumpToRemarkList(rr2, openid, page);
    }

    /**
     * 后台删除一条评论（在查询页面删除）
     *
     * @param remarkId 评论Id号
     * @return 返回视图ModelAndView，跳转到通过查询orderId得到的所有评论的页面
     */
    @RequestMapping("/admin/deletebyid")
    public ModelAndView deleteRemarkAdminById(@RequestParam String remarkId, @RequestParam String openid) {
        Remark r = remarkService.getRemarkByRemarkId(remarkId);
        RemarkResult2 rr2 = remarkService.deleteRemark(remarkId);
        return jumpToOrderIdRemarkList(rr2, r.getOrderId(), openid);
    }

    /**
     * 后台删除一条评论（在查询页面删除）
     *
     * @param remarkId 评论Id号
     * @return 返回视图ModelAndView，跳转到通过查询orderId得到的所有评论的页面
     */
    @RequestMapping("/admin/deleteintimescope")
    public ModelAndView deleteRemarkAdminTimeScope(@RequestParam String remarkId, @RequestParam String page, @RequestParam String openid) {
        /*Remark r = remarkService.getRemarkByRemarkId(remarkId);*/
        RemarkResult2 rr2 = remarkService.deleteRemark(remarkId);
        return jumpToRemarkList(rr2, lastStartTime, lastEndTime, page, openid);
    }

    /**
     * 后台更新一条评论
     * //@param remark 评论Remark类
     *
     * @return 返回包装结果类RemarkResult2
     */
    @RequestMapping("/admin/update")
    public ModelAndView updataRemarkAdmin(
            @ModelAttribute Remark remark, @RequestParam String openid, @RequestParam String page
    ) {

        Remark remark1 = remarkService.getRemarkByRemarkId(remark.getRemarkId());
        remark.setCreateTime(remark1.getCreateTime());
        RemarkResult2 rr2 = remarkService.updataRemark(remark);
        /*return rr2;*/
        return jumpToRemarkList(rr2, openid, page);
    }

    /**
     * 后台通过时间更新一条评论
     *
     * @param remark 评论Remark类
     * @return 返回包装结果类RemarkResult2
     */
    @PostMapping("/admin/updateintimescope")
    public ModelAndView updataRemarkAdminByTimeScope(@ModelAttribute Remark remark, String page, @RequestParam String openid) {
        Remark remark1 = remarkService.getRemarkByRemarkId(remark.getRemarkId());
        remark.setCreateTime(remark1.getCreateTime());
        RemarkResult2 rr2 = remarkService.updataRemark(remark);
        return jumpToRemarkList(rr2, lastStartTime, lastEndTime, page, openid);
    }

    /**
     * 后台更新一条评论（在查询页面更新）
     *
     * @param remark 评论Remark类
     * @return 返回视图ModelAndView，跳转到通过查询orderId得到的所有评论的页面
     */
    @PostMapping("/admin/updatebyid")
    public ModelAndView updataRemarkAdminById(@ModelAttribute Remark remark, String openid) {
        //remark在数据库中的creatTime字段不能更改，只在首次插入时赋值，修改只修改updateTime字段
        //所以更新时先获取原createTime字段值
        Remark remark1 = remarkService.getRemarkByRemarkId(remark.getRemarkId());
        remark.setCreateTime(remark1.getCreateTime());
        RemarkResult2 rr2 = remarkService.updataRemark(remark);
        return jumpToOrderIdRemarkList(rr2, remark.getOrderId(), openid);
    }

    /**
     * 通过订单id查询评论
     *
     * @param orderId 订单id
     * @param page    页数
     * @param size    一页多少条
     * @param openid  验证管理员用户
     * @return 返回视图
     */
    @GetMapping("/admin/byOrderId")
    public ModelAndView getAllByOrderIdAdmin(
            @RequestParam String orderId,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "2") Integer size,
            @RequestParam String openid) {
        Page[] pArr = new Page[1];
        remarkService.getAllRemarkByIdAdmin(orderId, page - 1, size, pArr);
        ModelAndView mm = new ModelAndView();
        mm.setViewName("/pan/remarkViewByOrderId");
        mm.addObject("pages", pArr[0]);
        mm.addObject("currentPage", page - 1);
        mm.addObject("size", size);
        mm.addObject("openid", openid);
        return mm;
    }


    @SuppressWarnings("all")
    @Autowired
    RemarkDao remarkDao;

    /**
     * 后台总评论
     *
     * @param page   页码
     * @param size   一页多少条
     * @param openid 验证管理员
     * @return 返回视图
     */
    @GetMapping("/admin/remarklist")
    public ModelAndView getAllPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "6") Integer size,
            @RequestParam String openid) {
        Page[] pArr = new Page[1];
        remarkService.getAllAdminPagable(page - 1, size, pArr);
        ModelAndView mm = new ModelAndView();
        mm.setViewName("/pan/allRemarkView");
        mm.addObject("pages", pArr[0]);
        mm.addObject("currentPage", page - 1);
        mm.addObject("size", size);
        mm.addObject("openid", openid);
        return mm;
    }


    private String lastStartTime = "2018-08-01 00:00:00";
    private String lastEndTime = "2020-08-01 00:00:00";

    /**
     * 通过时间范围查询
     *
     * @param page      页数
     * @param size      容量
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @return 视图
     */
    @GetMapping("/admin/byTimeScope")
    public ModelAndView getAllByTimeScopeAdmin(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "6") Integer size,
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestParam String openid) {
        if (startTime.equals("") || endTime.equals("")) {
            startTime = lastStartTime;
            endTime = lastEndTime;
        } else {
            String el = "([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))";
            Pattern p = Pattern.compile(el);
            if (!p.matcher(startTime).matches()) {
                startTime = lastStartTime;
            }
            if (!p.matcher(endTime).matches()) {
                endTime = lastEndTime;
            }
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 00:00:00";
            lastEndTime = endTime;
            lastStartTime = startTime;

        }
        Page[] pArr = new Page[1];
        remarkService.getAllRemarkByTimeScope(startTime, endTime, page - 1, size, pArr);
        ModelAndView mm = new ModelAndView();
        mm.setViewName("/pan/allRemarkViewByTimeScope");
        mm.addObject("pages", pArr[0]);
        mm.addObject("currentPage", page - 1);
        mm.addObject("size", size);
        mm.addObject("openid", openid);
        mm.addObject("startTime", startTime.substring(0, 10));
        mm.addObject("endTime", endTime.substring(0, 10));
        return mm;
    }

    /**
     * 页数按钮跳转方法
     *
     * @param page 页数
     * @param size 容量
     * @return 视图
     */
    @GetMapping("/admin/byTimeScope2")
    public ModelAndView getAllByTimeScopeAdmin(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "6") Integer size,
            @RequestParam String openid) {
        String startTime = lastStartTime;
        String endTime = lastEndTime;
        Page[] pArr = new Page[1];
        remarkService.getAllRemarkByTimeScope(startTime, endTime, page - 1, size, pArr);
        ModelAndView mm = new ModelAndView();
        mm.setViewName("/pan/allRemarkViewByTimeScope");
        mm.addObject("pages", pArr[0]);
        mm.addObject("currentPage", page - 1);
        mm.addObject("size", size);
        mm.addObject("openid", openid);
        mm.addObject("startTime", startTime.substring(0, 10));
        mm.addObject("endTime", endTime.substring(0, 10));
        return mm;
    }


    /**
     * 跳转公有方法，通过访问数据库后的回传结果验证是否成功,方法仅用于后台接口跳转
     *
     * @param rr2 封装好的结果类
     * @return 返回一个视图
     */
    private ModelAndView jumpToRemarkList(RemarkResult2 rr2, String openid) {
        if (rr2.getMcode() == 0) {
            ModelAndView error = new ModelAndView();
            error.setViewName("/pan/error");
            error.addObject("remarkresult2", rr2);
            return error;
        } else {
            return new ModelAndView("redirect:" + "http://localhost:8080/sell/remark/admin/remarklist?" + "&openid=" + openid);
        }
    }

    private ModelAndView jumpToRemarkList(RemarkResult2 rr2, String openid, String page) {
        if (rr2.getMcode() == 0) {
            ModelAndView error = new ModelAndView();
            error.setViewName("/pan/error");
            error.addObject("remarkresult2", rr2);
            return error;
        } else {
            ModelAndView mm = new ModelAndView("redirect:" + "http://localhost:8080/sell/remark/admin/remarklist?" + "&page=" + page + "&openid=" + openid);
            mm.addObject("page", page);
            /*mm.addObject("openid",openid);*/
            return mm;
        }
    }

    private ModelAndView jumpToRemarkList(RemarkResult2 rr2, String startTime, String endTime, String page, String openid) {
        if (rr2.getMcode() == 0) {
            ModelAndView error = new ModelAndView();
            error.setViewName("/pan/error");
            error.addObject("remarkresult2", rr2);
            return error;
        } else {
            ModelAndView modelAndView = new ModelAndView("redirect:" + "http://localhost:8080/sell/remark/admin/byTimeScope?page=" + page + "&startTime=" + startTime + "&endTime" + endTime + "&openid=" + openid);
            modelAndView.addObject("startTime", startTime.substring(0, 10));
            modelAndView.addObject("endTime", endTime.substring(0, 10));
            return modelAndView;
        }
    }

    /**
     * id查询接口的跳转公有方法，通过访问数据库后的回传结果验证是否成功,方法仅用于后台接口跳转
     *
     * @param rr2 封装好的结果类
     * @return 返回一个视图
     */
    private ModelAndView jumpToOrderIdRemarkList(RemarkResult2 rr2, String orderId, String openid) {
        if (rr2.getMcode() == 0) {
            ModelAndView error = new ModelAndView();
            error.setViewName("/pan/error");
            error.addObject("remarkresult2", rr2);
            return error;
        } else {
            return new ModelAndView("redirect:" + "http://localhost:8080/sell/remark/admin/byOrderId?orderId=" + orderId + "&openid=" + openid);
        }
    }


}
